<template>
    <div class="workflow-params">
        <div class="params-header">
            <h3>参数配置</h3>
            <div class="header-actions">
                <el-button-group>
                    <el-button 
                        type="primary" 
                        @click="handleAutoDetect"
                        :loading="detecting"
                    >
                        自动识别
                    </el-button>
                    <el-button @click="handleAddParam">
                        添加参数
                    </el-button>
                </el-button-group>
            </div>
        </div>

        <div class="params-list">
            <template v-if="params.length">
                <div 
                    v-for="(param, index) in params" 
                    :key="param.id"
                    class="param-wrapper"
                >
                    <div class="param-header">
                        <div class="param-info">
                            <el-input 
                                v-model="param.label" 
                                placeholder="参数名称"
                                class="param-label-input"
                            />
                            <el-select 
                                v-model="param.type"
                                placeholder="参数类型"
                                class="param-type-select"
                            >
                                <el-option
                                    v-for="type in paramTypes"
                                    :key="type.value"
                                    :label="type.label"
                                    :value="type.value"
                                />
                            </el-select>
                        </div>
                        <div class="param-actions">
                            <el-button-group>
                                <el-button 
                                    :disabled="index === 0"
                                    @click="moveParam(index, 'up')"
                                >
                                    <el-icon><ArrowUp /></el-icon>
                                </el-button>
                                <el-button 
                                    :disabled="index === params.length - 1"
                                    @click="moveParam(index, 'down')"
                                >
                                    <el-icon><ArrowDown /></el-icon>
                                </el-button>
                                <el-button 
                                    type="danger"
                                    @click="removeParam(index)"
                                >
                                    <el-icon><Delete /></el-icon>
                                </el-button>
                            </el-button-group>
                        </div>
                    </div>

                    <div class="param-content">
                        <component
                            :is="getParamComponent(param.type)"
                            v-model="param.value"
                            v-bind="param.config"
                            :label="param.label"
                            :help="param.help"
                            @update:modelValue="handleParamChange(param.id, $event)"
                        />
                        
                        <div class="param-config">
                            <el-collapse>
                                <el-collapse-item title="高级配置">
                                    <el-form label-position="top">
                                        <el-form-item label="节点 ID">
                                            <el-input v-model="param.nodeId" />
                                        </el-form-item>
                                        <el-form-item label="输入 ID">
                                            <el-input v-model="param.inputId" />
                                        </el-form-item>
                                        <el-form-item label="帮助信息">
                                            <el-input 
                                                v-model="param.help"
                                                type="textarea"
                                                rows="2"
                                            />
                                        </el-form-item>
                                        <el-form-item label="默认值">
                                            <el-input 
                                                v-model="param.defaultValue"
                                                :type="param.type === 'number' ? 'number' : 'text'"
                                            />
                                        </el-form-item>
                                    </el-form>
                                </el-collapse-item>
                            </el-collapse>
                        </div>
                    </div>
                </div>
            </template>
            <el-empty v-else description="暂无参数配置">
                <template #extra>
                    <el-button type="primary" @click="handleAutoDetect">
                        自动识别参数
                    </el-button>
                </template>
            </el-empty>
        </div>

        <div class="params-footer">
            <el-button @click="handlePrev">上一步</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowUp, ArrowDown, Delete } from '@element-plus/icons-vue';
import { getParamComponent, ParamType } from './params';
import type { WorkflowTemplate, ParamNode } from '@/types';

const props = defineProps<{
    workflow?: Partial<WorkflowTemplate>;
}>();

const emit = defineEmits<{
    (e: 'prev'): void;
    (e: 'save', params: ParamNode[]): void;
}>();

const params = ref<ParamNode[]>([]);
const detecting = ref(false);

// 参数类型选项
const paramTypes = [
    { label: '文本', value: ParamType.Text },
    { label: '数字', value: ParamType.Number },
    { label: '选择器', value: ParamType.Select },
    { label: '开关', value: ParamType.Boolean },
    { label: '滑块', value: ParamType.Slider },
    { label: '颜色', value: ParamType.Color },
    { label: '图片', value: ParamType.Image },
    { label: '模型', value: ParamType.Model },
    { label: '标签', value: ParamType.Tags },
    { label: '画布', value: ParamType.Canvas }
];

// 自动识别参数
const handleAutoDetect = async () => {
    if (!props.workflow?.comfyuiJson) {
        ElMessage.warning('请先配置工作流 JSON');
        return;
    }

    detecting.value = true;
    try {
        const json = typeof props.workflow.comfyuiJson === 'string' 
            ? JSON.parse(props.workflow.comfyuiJson)
            : props.workflow.comfyuiJson;

        const nodes = json.nodes || {};
        const detectedParams: ParamNode[] = [];

        for (const [nodeId, node] of Object.entries(nodes)) {
            const paramType = autoDetectParamType(node);
            if (paramType) {
                detectedParams.push({
                    id: `${nodeId}_${Date.now()}`,
                    nodeId,
                    inputId: '',
                    type: paramType,
                    label: node.title || nodeId,
                    value: null,
                    defaultValue: null,
                    config: getDefaultConfig(paramType),
                    help: `节点 ID: ${nodeId}`
                });
            }
        }

        params.value = detectedParams;
        ElMessage.success(`检测到 ${detectedParams.length} 个参数`);
    } catch (error) {
        console.error('Auto detect params error:', error);
        ElMessage.error('参数识别失败');
    } finally {
        detecting.value = false;
    }
};

// 添加参数
const handleAddParam = () => {
    params.value.push({
        id: `param_${Date.now()}`,
        nodeId: '',
        inputId: '',
        type: ParamType.Text,
        label: '新参数',
        value: null,
        defaultValue: null,
        config: {},
        help: ''
    });
};

// 移动参数
const moveParam = (index: number, direction: 'up' | 'down') => {
    const newIndex = direction === 'up' ? index - 1 : index + 1;
    if (newIndex < 0 || newIndex >= params.value.length) return;
    
    const temp = params.value[index];
    params.value[index] = params.value[newIndex];
    params.value[newIndex] = temp;
};

// 删除参数
const removeParam = (index: number) => {
    params.value.splice(index, 1);
};

// 参数值变化
const handleParamChange = (id: string, value: any) => {
    const param = params.value.find(p => p.id === id);
    if (param) {
        param.value = value;
    }
};

// 获取参数默认配置
const getDefaultConfig = (type: ParamType) => {
    switch (type) {
        case ParamType.Number:
        case ParamType.Slider:
            return { min: 0, max: 100, step: 1 };
        case ParamType.Select:
            return { options: [] };
        case ParamType.Boolean:
            return { activeText: '是', inactiveText: '否' };
        case ParamType.Color:
            return { showAlpha: true };
        default:
            return {};
    }
};

// 处理上一步
const handlePrev = () => {
    emit('prev');
};

// 处理保存
const handleSave = () => {
    // 验证参数配置
    const invalidParams = params.value.filter(
        param => !param.label || !param.nodeId || !param.inputId
    );

    if (invalidParams.length > 0) {
        ElMessage.warning('请完善参数配置');
        return;
    }

    emit('save', params.value);
};

// 监听工作流变化
watch(() => props.workflow?.params, (newParams) => {
    if (newParams?.length) {
        params.value = JSON.parse(JSON.stringify(newParams));
    }
}, { immediate: true });
</script>

<style lang="scss" scoped>
.workflow-params {
    padding: 20px;

    .params-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 500;
        }
    }

    .params-list {
        margin-bottom: 30px;
        min-height: 200px;
    }

    .param-wrapper {
        margin-bottom: 24px;
        padding: 16px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;

        &:hover {
            border-color: #409eff;
        }
    }

    .param-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
    }

    .param-info {
        display: flex;
        gap: 12px;
        flex: 1;

        .param-label-input {
            width: 200px;
        }

        .param-type-select {
            width: 120px;
        }
    }

    .param-content {
        padding: 0 12px;
    }

    .param-config {
        margin-top: 16px;
    }

    .params-footer {
        display: flex;
        justify-content: center;
        gap: 20px;
        padding-top: 20px;
        border-top: 1px solid #ebeef5;
    }
}
</style>